<template>
  <a-card class="business" :title="pageName" size="small">
    <el-link slot="extra" type="primary" @click="returnParentPage"><i class="fa-solid fa-angles-left"></i> 返回上一级</el-link>
    <el-form ref="menuDataForm" :model="menuNewData" :rules="newMenuRules" label-width="6vw">
      <!--第一行信息录入-->
      <el-row type="flex" justify="space-between" style="margin-top: 25px">
        <el-col :span="6">
          <el-form-item label="上级菜单" prop="parentId">
            <a-tree-select :treeData="parentMenus" v-model="menuNewData.parentId" placeholder="请选择上级菜单..." @change="selectParentMenu"
                           :dropdown-style="{maxHeight: '400px', overflow: 'auto' }" allow-clear style="width: 100%" size="large"
                           tree-default-expand-all />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="菜单名称" prop="name">
            <el-input v-model="menuNewData.name" placeholder="请输入菜单名称..." maxlength="8" @blur="menuNewData.name = menuNewData.name.trim()"
                      show-word-limit clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="菜单别名" prop="alias">
            <el-tooltip content="输入菜单的英文别名" placement="bottom-start">
              <el-input v-model="menuNewData.alias" placeholder="请输入菜单别名..." maxlength="16" @blur="menuNewData.alias = menuNewData.alias.trim()"
                        show-word-limit clearable/>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="菜单类型" prop="type">
            <el-select v-model="menuNewData.type" placeholder="请选择菜单类型..." maxlength="16" show-word-limit clearable style="width: 100%">
              <el-option value="0" label="菜单"/>
              <el-option value="1" label="按钮"/>
              <el-option value="2" label="其它"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!--第二行信息录入-->
      <el-row type="flex" justify="space-between" style="margin-top: 20px">
        <el-col :span="24">
          <el-form-item label="菜单功能" prop="features">
            <el-input v-model="menuNewData.features" type="textarea" placeholder="请输入菜单功能..." maxlength="64"  :autosize="{ minRows: 3, maxRows: 6}"
                      show-word-limit clearable style="width: 100%" @blur="menuNewData.features = menuNewData.features.trim()"/>
          </el-form-item>
        </el-col>
      </el-row>
      <!--第三行信息录入-->
      <el-row type="flex" justify="space-between" style="margin-top: 20px">
        <el-col :span="6">
          <el-form-item label="适用系统" prop="roleId">
            <el-select v-model="menuNewData.roleId" placeholder="请选择适用系统..." show-word-limit clearable style="width: 100%">
              <el-option value="0" label="信息管理系统"/>
              <el-option value="1" label="客户系统"/>
              <el-option value="2" label="合作者系统"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="授权标识" prop="permission">
            <el-tooltip content="示例：xxx:xxx:xxx" placement="bottom-start">
              <el-input v-model="menuNewData.permission" placeholder="请输入菜单所需授权标识..." maxlength="32" show-word-limit clearable
                        @blur="menuNewData.permission = menuNewData.permission.trim()"/>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="对应图标" prop="iconClass">
            <el-input v-model="menuNewData.iconClass" placeholder="请输入菜单代表图标..." maxlength="64" show-word-limit clearable
                      @blur="menuNewData.iconClass=menuNewData.iconClass.trim()"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="菜单排序号" prop="sort">
            <el-tooltip :content="existSortNum" placement="top-start">
              <el-input-number v-model="menuNewData.sort" :min="1" size="medium" style="width: 100%"/>
            </el-tooltip>
          </el-form-item>
        </el-col>
      </el-row>
      <!--第四行信息录入-->
      <el-row type="flex" style="margin-top: 20px">
        <el-col :span="6">
          <el-form-item label="跳转路径" prop="path">
            <el-input v-model="menuNewData.path" placeholder="请输入菜单触发路由跳转路径..." maxlength="32" show-word-limit clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="componentDir" label="组件目录">
            <a-tree-select :treeData="treeSelectData" v-model="menuNewData.comDir" style="width: 100%;" size="large"
                           :dropdown-style="{maxHeight: '400px', overflow: 'auto' }" placeholder="请输入页面所有目录..." allow-clear tree-default-expand-all>
            </a-tree-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="组件名" prop="componentName">
            <el-input v-model="menuNewData.comName" placeholder="请输入跳转组件号..." maxlength="16" show-word-limit clearable/>
            <!--            <input type="file" id="file" hidden @change="fileChange"/>
                        <el-input placeholder="请选择跳转组件..." v-model="menuNewData.componentName" readonly class="input-with-select">
                          <el-button slot="append" icon="el-icon-folder" type="success" @click="btnChange"></el-button>
                        </el-input>-->
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="页面标题" prop="componentAlias">
            <el-input v-model="menuNewData.comAlias" placeholder="请输入跳转页面的标题..." maxlength="32" show-word-limit clearable/>
          </el-form-item>
        </el-col>
      </el-row>
      <!--确定|取消按钮-->
      <el-row type="flex" justify="end" style="margin-top: 25vh">
        <el-col :span="5">
          <el-form-item align="end">
            <el-button @click="$refs.menuDataForm.resetFields()">取消</el-button>
            <el-button type="danger" @click="submitNewMenuData">提交</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

  </a-card>
</template>
import {Tooltip, InputNumber} from "element-ui";
<script>

function dataConverFatherAndChildrenNode(parentMenus)
{
  if(!Array.isArray(parentMenus))
    return null;
  parentMenus = parentMenus.filter(item => !item.type);
  let menuMap = new Map;
  parentMenus.forEach((item) =>
  {
    menuMap.set(item.id, item);
  })
  let target = [];
  parentMenus.forEach((item) =>
  {
    let parent = menuMap.get(item.parentId);
    if (!parent)
    {
      target.push(item);
    } else
    {
      if (!Array.isArray(parent.children))
      {
        parent.children = [];
      }
      parent.children.push(item);
    }
  });
  return target;
}

export default {
  name: "MenuAddAndUpdate",
  data(){
    /*排序号自定义校验规则*/
    const sortValid = (rule, value, callback) => {
      let sortNums = [];
      if(this.menuNewData.parentId)
        sortNums = generatedSortNum(this.menuNewData.parentId, JSON.parse(localStorage.getItem("menusData")));
      else
        sortNums = generatedSortNum(0, JSON.parse(localStorage.getItem("menusData")));

      if((this.$route.path === "/menu/add" && sortNums.includes(value)) || (this.$route.path === "/menu/update" && this.oldMenuData.sort !== value && sortNums.includes(value)) )
        return callback(new Error("该排序号已被使用，请重新选择！"));
      callback();
    };
    /*上级菜单自定义校验规则*/
    const parentValid = (rule,value,callback) => {
      if(!this.option)
      {
        return callback();
      }
      let menus = null;
      if(localStorage.getItem("menusData") === 'undefined')
      {
        return callback();
      }
      menus = JSON.parse(localStorage.getItem("menusData"));
      let childrens = menus.filter(item => item.parentId === this.oldMenuData.id).map(item => item.id);
      if(childrens.includes(value) || value === this.oldMenuData.id)
        return callback(new Error("不能以自身或其子菜单为上级菜单，请重新选择！"));
      callback();
    };
    /*组件别名校验规则*/
    const componentAliasValid = (rule, value, callback) => {
      if((this.menuNewData.path || this.menuNewData.type === '0') && !value)
        return callback(new Error("系统UI要求对应页面标题不能为空，请输入！"));
      callback();
    }
    /*绑定的变量*/
    return{
      option: undefined,
      pageName: this.$route.meta.title,
      menuNewData:{
        id: undefined,
        name: "",
        alias: "",
        type: "",
        features: "",
        path: "",
        comDir: undefined,
        comName: "",
        comAlias: "",
        roleId: undefined,
        permission: "",
        iconClass: "",
        parentId: undefined,
        parentName: "",
        routerParentId: "",
        enabled:"",
        sort: 1,
        createdDate: "",
        createdUser: "",
        modifiedDate: "",
        modifiedUser: "",
      },
      /*表单校验规则*/
      newMenuRules: {
        /*name: [
          {required: true, message: "菜单名称不能为空！", trigger: "blur"}
        ],
        alias: [
          {required: true, message: "菜单别名不能为空！", trigger: "blur"},
          {pattern: /^[a-z]*$/g, message: "菜单别名只能由英文小写字母组成！", trigger: "blur"}
        ],
        features: [
          {required: true, message: "菜单功能不能为空！", trigger: "blur"}
        ],
        type: [
          {required: true, message: "菜单类型不能为空！", trigger: "change"}
        ],
        roleId: [
          {required: true, message: "适用系统不能为空！", trigger: "change"}
        ],
        iconClass: [
          {required: true, message: "对应图标不能为空！", trigger: "blur"}
        ],
        sort: [
          {validator: sortValid, trigger: "change"}
        ],
        permission: [
          {pattern: /^[a-z]*:[a-z]*:[a-z]*$/g, message: "授权标识错误，请求按示例输入！", trigger: "blur"}
        ],
        parentId: [
          {validator: parentValid, trigger: "change"}
        ],
        componentAlias: [
          {validator: componentAliasValid, trigger: "blur"}
        ]*/
      },
      treeSelectData: [],
      parentMenus: [],
      existSortNum: "",
      oldMenuData: undefined
    }
  },
  methods:{
    /*构建上级菜单树形选择器数据*/
    generateParentMenusTreeSelectNode(source)
    {
      if(!Array.isArray(source))
        return null;
      let parentMenus = [];
      parentMenus = source.filter(item => {
        return item.type === 0 && item.enabled;
      }).map(item => {
        let parentMenu = {};
        parentMenu.id = item.id;
        parentMenu.parentId = item.parentId;
        parentMenu.value = item.id;
        parentMenu.title = item.name;
        parentMenus.push(parentMenu);
        return parentMenu;
      })
      return dataConverFatherAndChildrenNode(parentMenus);
    },
    /*获取所有菜单数据，为构建上级菜单树形选择器数据做准备*/
    async generateParentMenusTreeSelect() {

    },
    /*树形选择器change事件处理函数，用于菜单排序号InputNumberUI初始化*/
    selectParentMenu(value, node, extra)
    {

    },
    /*文件input的change事件处理函数*/

    /*提交按钮点击事件处理函数*/
    btnChange(){
      var file = document.getElementById("file");
      file.click();
    },
    async submitNewMenuData() {
      /*发起请求,menuNewData对象作为参数传递给服务器,请求方式:post,请求url/menu*/
      const res = await this.$http.post("/menu",this.menuNewData)
      console.log(res)
    },
    /*返回上一级*/
    returnParentPage()
    {

    }
  },
  created() {

  },
}
</script>

<style scoped>

</style>